/*
 * @Author: xiaoyan
 * @Date: 2021-09-10 11:09:16
 * @LastEditors: xiaoyan
 * @LastEditTime: 2021-09-10 11:35:21
 * @Description: 请求文件配置
 * @FilePath: \vue-ts-basic\src\utils\request.ts
 */
import axios from 'axios'
import { Message } from 'element-ui'
import {UserModule} from '@/store/modules/user'
import { getToken,removeToken} from '@/utils/storage'
import Router from "@/router";

// create an axios instance
const service = axios.create({
  baseURL: '', // api 的 base_url
  timeout: 50000 // request timeout
})
// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    if (UserModule.token) {
      // 让每个请求携带token-- ['auth']为自定义key 请根据实际情况自行修改
      config.headers['auth'] = getToken()
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => response.data,
  
  error => {
    if(error.response){
      switch (error.response.status) {
        case 401:
        case 403: {
          removeToken();
          Router.push({
            path: "/login"
          });
          break;
        }
      }
    }else{
      Message({
        message: errTip(error.message),
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

function errTip(msg:string){
  if(msg.indexOf("timeout") != -1){
    return "请求超时！";
  }else if(msg.indexOf("Network Error") != -1){
    return "无法连接网络！";
  }else{
    return msg;
  }
}
export  {service as request }